package com.boarsoft.boar.proj.biz;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.dir.DirBiz;
import com.boarsoft.boar.entity.DirInfo;
import com.boarsoft.boar.entity.ProjInfo;
import com.boarsoft.boar.proj.ProjBiz;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("projBiz")
public class ProjBizImpl extends SimpleBizImpl implements ProjBiz {
	@Autowired
	private DirBiz dirBiz;

	@Override
	@Transactional(readOnly = true)
	public PagedResult<ProjInfo> list(String key, String orderBy, int pageNo, int pageSize) {
		StringBuilder sb = new StringBuilder();
		if (Util.strIsNotEmpty(key)) {
			sb.append(" and (p.code like '%").append(key);
			sb.append("%' or p.name like '%").append(key);
			sb.append("%' or p.memo like '%").append(key);
			sb.append("%')");
		}

		String totalSql = new StringBuilder().append("select count(p.id) from ").append(ProjInfo.class.getName())
				.append(" p where EXISTS (select d.id from ").append(DirInfo.class.getName()).append(" d where d.id=p.id) ")
				.append(sb).toString();
		int total = dao.getTotal(totalSql);
		if (Util.strIsNotEmpty(orderBy)) {
			sb.append(" order by ").append(orderBy);
		} else {
			sb.append(" order by p.code");
		}
		String sql = new StringBuilder().append("select p from ").append(ProjInfo.class.getName())
				.append(" p where EXISTS (select d.id from ").append(DirInfo.class.getName()).append(" d where d.id=p.id) ")
				.append(sb).toString();
		List<ProjInfo> lt = dao.list(sql, pageNo, pageSize);
		return new PagedResult<ProjInfo>(total, lt, pageNo, pageSize);
	}

	@Override
	@Transactional
	public ReplyInfo<Object> add(DirInfo d, ProjInfo a) {
		// 先添加DirInfo
		dirBiz.add(d);
		log.info("Save DirInfo {}", d.getId());
		// 父系统ID，找不到就是null
		String ppId = dirBiz.lookup(d, DirInfo.TYPE_PROJ);
		// 根据节点类型同步保存AppInfo或FlowInfo
		ProjInfo o = new ProjInfo();
		o.setId(d.getId());
		o.setParentId(ppId); //父系统ID，可以为空
		o.setCode(d.getCode());// 应用编号
		o.setName(d.getName());
		o.setSourcePath(a.getSourcePath());
		o.setVer(a.getVer());
		o.setStatus(a.getStatus());
		o.setSourceCode(a.getSourceCode());
		o.setExportCode(a.getExportCode());
		o.setCompileCode(a.getCompileCode());
		o.setDeployCode(a.getDeployCode());
		o.setMemo(a.getMemo());
		o.setCreateTime(a.getCreateTime());
		o.setLastTime(a.getLastTime());
		// 再保存proj_info
		dao.save(o);
		return new ReplyInfo<Object>(true, d);
	}

	@Override
	@Transactional
	public void delete(String id) {
		dao.delete(ProjInfo.class, id);
		// 由附加的切面执行其它的关联操作，其切面为：sourceBizImpl
	}

	@Override
	@Transactional
	public ReplyInfo<Object> update(DirInfo d, ProjInfo a) {
		dirBiz.update(d);
		dao.merge(a);
		return new ReplyInfo<Object>(true, d);
	}

	@Override
	@Transactional(readOnly = true)
	public ProjInfo get(String id) {
		ProjInfo o = dao.get(ProjInfo.class, id);
		//dao.evict(o);
		return o;
	}

	private boolean startProj(String id) {
		boolean ret = false;
		ProjInfo o = (ProjInfo) dao.get(ProjInfo.class, id);
		if (o == null) {
			log.info("启用系统操作proj_info表失败，id={}，原因：根据系统id查询系统返回为空！", id);
			return false;
		}
		if (o.getStatus() != ProjInfo.STATUS_NOUSE) {
			log.info(JSON.toJSONString("系统id=" + id + "当前已处于启用状态，无需再次启用！"));
			ret = true;
		} else {
			o.setStatus(ProjInfo.STATUS_INUSE);
			ret = true;
		}
		return ret;
	}

	@Override
	@Transactional
	public boolean start(String id) {
		boolean ret1 = false, ret2 = false;
		String[] IDS = id.split(",");
		for (String ID : IDS) {
			ret1 = this.startProj(ID);// 在proj_info表启用系统本身
			ret2 = dirBiz.start(ID);// 在dir_info表启用应用
		}
		return ret1 && ret2;
	}

	private boolean stopProj(String id) {
		boolean ret = false;
		ProjInfo o = (ProjInfo) dao.get(ProjInfo.class, id);
		if (o == null) {
			log.info(JSON.toJSONString("停用系统操作proj_info表失败，id=" + id + "，原因：根据系统id=" + id + "查询系统返回为空！"));
		}
		if (o.getStatus() != ProjInfo.STATUS_INUSE) {
			log.info(JSON.toJSONString("系统id=" + id + "当前已处于停用状态，无需再次停用！"));
			ret = true;
		} else {
			o.setStatus(ProjInfo.STATUS_NOUSE);
			ret = true;
		}
		return ret;
	}

	@Override
	@Transactional
	public boolean stop(String id) {
		boolean ret1 = false, ret2 = false;
		String[] IDS = id.split(",");
		for (String ID : IDS) {
			ret1 = this.stopProj(ID);// 在proj_info表停用系统本身
			ret2 = dirBiz.stop(ID);// 在dir_info表停用系统
		}
		return ret1 && ret2;
	}

	@Override
	@Transactional
	public String copy(String sourceId, String parentId, String newId) {
		ProjInfo o = this.get(sourceId);
		ProjInfo n = this.transfer(o, ProjInfo.class);
		n.setId(newId);// //应用的id来自于前一步骤的dir_info表id
		n.setCreateTime(Util.getStdmfDateTime());
		n.setLastTime(Util.getStdmfDateTime());
		dao.save(n);
		return newId;
	}
}